package org.bitmap.mm.util;

import java.util.concurrent.LinkedBlockingQueue;

import android.os.Message;

 class LoveBitmapTask extends Thread {

	LinkedBlockingQueue<ImageData> queue = new LinkedBlockingQueue<ImageData>();
	private boolean running = false;
	private LoveBitmapHandler loveBitmapHandler;
	private LoveBitmapManager loveBitmapManager;

	public LoveBitmapTask(LoveBitmapManager love, LoveBitmapHandler handler) {
		loveBitmapHandler = handler;
		loveBitmapManager = love;
	}

	public void addBitmapInfo(ImageData info) {
		synchronized (queue) {
			if(!queue.contains(info)){
				queue.add(info);
			}
		}
	}
	public void clear()
	{
		if(queue!=null)
			queue.clear();
	}
	@Override
	public void run() {
		setRunning(true);
		while (isRunning()) {
			try {
				ImageData info = queue.take();
				if (!loveBitmapManager.isExitTasksEarly()) {
					HttpLove.downloadBitmapToFile(
							loveBitmapManager.getContext(),
							String.valueOf(info));
					Message msg = loveBitmapHandler
							.obtainMessage(LoveBitmapHandler.STATE_BITMAP_SET);
					msg.obj = info;
					loveBitmapHandler.sendMessage(msg);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
				System.gc();
			} catch (Exception ex) {
				ex.printStackTrace();
				System.gc();
			}
		}

	}

	public boolean isRunning() {
		return running;
	}

	public void setRunning(boolean running) {
		this.running = running;
	}

}
